<?php
class InviteCodes extends BaseModel
{
	protected $res;
	protected $expire;
	public function getSource()
    {
        return "f_invite_codes";
    }

	public function usedInviteCode(){
        $conditions = "used = 0";
        $first_one = $this->findFirst(
            array(
                "conditions" => $conditions,
                "order" => 'RAND()',
                'limit' =>1,
            )
        );

        if(!empty($first_one)){
            $inviteCodes = $first_one->toarray();
            $code1=str_pad($inviteCodes['id'],6,"0",STR_PAD_LEFT);      //不足6位前面补0
            $user = new Member();
            $is_invitecode = $user->find_by_inviteCode($inviteCodes['id']);
            if($is_invitecode){
                $this->usedInviteCode();
            }
            $params['created_at'] = date('Y-m-d H:i:s',time());
            $params['updated_at'] = date('Y-m-d H:i:s',time());
            $params['used'] = 1;
            $params['id'] = $inviteCodes['id'];
            $result = $this->save($params);
        }else{
            $result = $this->createinvite();
        }
        if($result){
            return $code1;
        }else{
            return $this->createinvite();
        }
    }



    private function createinvite(){
        $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $rand = $code[rand(0,25)]
            .strtoupper(dechex(date('m')))
            .date('d')
            .substr(time(),-5)
            .substr(microtime(),2,5)
            .sprintf('%02d',rand(0,99));
        for(
            $a = md5( $rand, true ),
            $s = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
            $d = '',
            $f = 0;
            $f < 6;
            $g = ord( $a[ $f ] ),
            $d .= $s[ ( $g ^ ord( $a[ $f + 8 ] ) ) - $g & 0x1F ],
            $f++
        );
        $user = new Member();
        $is_invitecode = $user->find_by_inviteCode($d);
        if($is_invitecode){
            $this->createinvite();
        }
        return $d;
    }


    /**
     * @func 根据id返回记录
     */
    public function findbyUserId($id){
        return $this->findFirstByUserId($id);
    }


    /**
     * 保存验证码
     */
    public function save_invite($params){
        return $this->save($params);
    }


    /**
     * @func 根据id返回记录
     */
    public function findbyId($id){
        $result = $this->findFirstById($id);
        if($result){
            return $result->toarray();
        }else{
            return null;
        }
    }

}
